﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using CoreEx.Database.Client;
using CoreEx.Database.Metadata;
using LinFu.IoC.Configuration;
using LinFu.IoC.Interfaces;
using LinFu.IoC;
namespace CoreEx.Database.MetaData.Implementation
{
    [Factory(typeof(IMetadataRepository))]
    public class MetadataRepositoryFactory : IFactory<IMetadataRepository>
    {
        private static readonly IDictionary<string,IMetadataRepository> _repositories 
            = new Dictionary<string, IMetadataRepository>();

        
                   
        public IMetadataRepository CreateInstance(IFactoryRequest request)
        {
            lock (_repositories)
            {
                var repositoryName = request.ServiceName;
                if (string.IsNullOrEmpty(repositoryName))
                    repositoryName = request.Container.GetService<IConnectionInfo>().Name;

                if (!_repositories.ContainsKey(repositoryName))
                {

                    bool loadFromStorage = true;
                    if (request.Arguments.Length > 0 && request.Arguments[0] is bool)
                        loadFromStorage = (bool) request.Arguments[0];


                    var storage = request.Container.GetService<IRepositoryStorage>();

                    if (loadFromStorage && storage.Contains(repositoryName))
                        _repositories.Add(repositoryName, storage.Load(repositoryName));
                    else
                    {
                        var loader =
                            request.Container.GetService<IMetadataRepositoryLoader>(new object[] {repositoryName});
                        _repositories.Add(repositoryName,
                                          new MetadataRepository(repositoryName, loader.LoadTables()));
                        storage.Save(_repositories[repositoryName]);
                    }
                }
                return _repositories[repositoryName];
            }
        }
    }
}
